<template>
	<jk-dialog
		v-model="showDialog"
		title="配置-设备保养项目"
		width="940px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" label-width="110px" :show-message="false">
			<el-tag type="primary" effect="plain" class="margin-bottom-4">
				<span class="el-icon-tickets item-gap"></span>
				<span>保养机台</span>
			</el-tag>
			<jk-card class="margin-bottom-10">
				<el-row ref="box1">
					<el-col :span="8">
						<el-form-item class="margin-bottom-0" label="设备名称">
							<span class="read-only-2">{{ ruleForm.name }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-0" label="工序">
							<span class="read-only-2">{{ ruleForm.processName }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-0" label="车间">
							<span class="read-only-2">{{ ruleForm.workshopName }}</span>
						</el-form-item>
					</el-col>
				</el-row>
			</jk-card>
		</el-form>
		<div class="flex-between-center margin-bottom-4">
			<el-button size="mini" class="el-icon-plus" type="primary" @click="onAddBtn">保养项目</el-button>
			<div class="flex-start-center">
				<jk-state-bar v-for="(item) in upkeepStateList" :key="item.id" :state="item.id" :state-list="upkeepStateList" class="margin-left-10"></jk-state-bar>
			</div>
		</div>
		<jk-table :max-height="dialogTableHeight - 42" border :data="ruleForm.itemList">
			<vxe-column title="序号" align="center" field="sortNum" :width="50">
				<template slot-scope="scope">
					<span>{{ scope.row.sortNum }}</span>
				</template>
			</vxe-column>
			<vxe-column title="项目名称" align="left" field="upkeepItemName" :min-width="140">
				<template slot-scope="scope">
					<div class="flex-start-center">
						<jk-state-bar :state-list="upkeepStateList" :show-text="false" :state="scope.row.upkeepState"></jk-state-bar>
						<span>{{ scope.row.upkeepItemName }}</span>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="周期" align="left" field="cycleUnit" :min-width="140">
				<template slot-scope="scope">
					<span>{{ transferCircleUnit(scope.row) }}</span>
				</template>
			</vxe-column>
			<vxe-column title="上次保养时间" align="left" field="lastUpkeepEndTime" :width="150" />
			<!--<vxe-column title="计划保养人" align="left" field="empName" :min-width="110">
				<template slot="header">
					<div class="flex-between-center">
						<span>计划保养人</span>
						<el-popover width="240" trigger="click" title="批量设置">
							<remote-search-emp-input
								:append-to-body="true"
								size="small"
								placeholder="保养人"
								only-key="empId"
								query-name="empName"
								:form-data="{}"
								@on-select="onGlobalSelectEmpChangeFromTable"
							></remote-search-emp-input>
							<el-button slot="reference" icon="el-icon-edit" type="text" size="mini"></el-button>
						</el-popover>
					</div>
				</template>
				<template slot-scope="scope">
					<remote-search-emp-input
						:append-to-body="true"
						size="mini"
						placeholder="保养人"
						only-key="empId"
						query-name="empName"
						:form-data="scope.row"
						:disabled="scope.row.upkeepState !== 0"
						@on-select="onSelectEmpChangeFromTable($event, scope.rowIndex)"
					></remote-search-emp-input>
				</template>
			</vxe-column>-->
			<vxe-column title="计划保养时间" align="left" field="planUpkeepTime" :width="210">
				<template slot="header">
					<div class="flex-between-center">
						<span>计划保养时间</span>
						<el-popover width="240" trigger="click" title="批量设置">
							<jk-date-picker v-model="globalTime" class="width-100-percent" type="datetime" size="small" @change="onGlobalTimeChange"></jk-date-picker>
							<el-button slot="reference" icon="el-icon-edit" type="text" size="mini"></el-button>
						</el-popover>
					</div>
				</template>
				<template slot-scope="scope">
					<jk-date-picker v-model="scope.row.planUpkeepTime" :disabled="scope.row.upkeepState !== 0" class="width-100-percent" type="datetime" size="mini"></jk-date-picker>
				</template>
			</vxe-column>
			<vxe-column title="操作" align="center" field="operation" :width="70">
				<template slot-scope="scope">
					<el-button :disabled="scope.row.upkeepState !== 0" icon="el-icon-delete" size="mini" @click="onDeleteRowBtn(scope)"></el-button>
				</template>
			</vxe-column>
		</jk-table>
		<checkbox-upkeep-item-dialog
			check-key-name="upkeepItemId"
			:default-process-id="ruleForm.processId"
			:default-select-rows="ruleForm.itemList"
			:dialog-state="checkboxUpkeepItemDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxUpkeepItemDialog"
			@on-confirm="onConfirmBtnOfCheckboxUpkeepItemDialog"
		></checkbox-upkeep-item-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import remoteSearchEmpInput from '../../../production/order/components/remote-search-emp-input';
    import checkboxUpkeepItemDialog from './checkbox-upkeep-item-dialog';
    import {
        machineManagerUpkeepMachineJobMachineDetails,
        machineManagerUpkeepMachineJobUpdateMachineAndItem
    } from '../../../../api/machine/machineUpkeepItemConfig';
    import { upkeepStateList } from '../../../../utils/jk/status-option-list';
    import { formatTime, tipsBar } from '../../../../utils/jk/jk-tool';
    import { machineManagerUpkeepMachineJobUpdateUpkeepJobMachine } from '../../../../api/machine/machineUpkeepItemConfig';
    import upkeepMixin from '../upkeepItemPlan/upkeep';
    export default {
        mixins: [calHeight, upkeepMixin],
        components: {
            checkboxUpkeepItemDialog,
            remoteSearchEmpInput
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: Number,
                default: 0
            },
            dataIds: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                upkeepStateList: upkeepStateList.filter(x => x.id !== 3),
                globalTime: '',
                checkboxUpkeepItemDialogState: false,
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    workshopId: null,
                    workshopName: null,
                    empId: null,
                    empName: '',
                    machineId: null,
                    machineCode: null,
                    machineName: null,
                    itemList: []
                },
                rules: {
                    empId: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onGlobalSelectEmpChangeFromTable(e) {
                if (Object.keys(e).length) {
                    this.ruleForm.itemList.forEach(x => {
                        if (x.upkeepState === 0) {
                            this.$set(x, 'empId', e.id);
                            this.$set(x, 'empName', e.name);
                        }
                    });
                }
            },
            onGlobalTimeChange(e) {
                this.ruleForm.itemList.forEach(x => {
                    if (x.upkeepState === 0) {
                        this.$set(x, 'planUpkeepTime', e);
                    }
                });
            },
            onAddBtn() {
                this.checkboxUpkeepItemDialogState = true;
            },
            onConfirmBtnOfCheckboxUpkeepItemDialog(data) {
                data.forEach(x => {
                    this.ruleForm.itemList.push({
                        'sortNum': x.sortNum,
                        'cycleMax': x.cycleMax,
                        'cycleMin': x.cycleMin,
                        'cycleUnit': x.cycleUnit,
                        'upkeepTypeId': x.upkeepTypeId,
                        'upkeepTypeCode': x.upkeepTypeCode,
                        'upkeepTypeName': x.upkeepTypeName,
                        'upkeepItemCode': x.code,
                        'upkeepItemId': x.id,
                        'upkeepItemName': x.name,
                        'upkeepState': 0,
                        'planUpkeepTime': ![4, 5].includes(x.cycleUnit) ? formatTime(Date.now()) : ''
                    });
                });
                this.checkboxUpkeepItemDialogState = false;
            },
            onVisibleChangeOfCheckboxUpkeepItemDialog(e) {
                this.checkboxUpkeepItemDialogState = e;
            },
            onDeleteRowBtn(scope) {
                this.$delete(this.ruleForm.itemList, scope.rowIndex, 1);
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'empId', e.id);
                    this.$set(this.ruleForm, 'empName', e.name);
                }
            },
            onSelectEmpChangeFromTable(e, rowIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.itemList[rowIndex], 'empId', e.id);
                    this.$set(this.ruleForm.itemList[rowIndex], 'empName', e.name);
                }
            },
            createAndUpdateRequest() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                // if (params.itemList.length) {
                this.saveBtnLoading = true;
                machineManagerUpkeepMachineJobUpdateUpkeepJobMachine(params).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
                /* } else {
                    tipsBar(this, 'custom', 'warning', '当前没有可修改的数据,无需保存!');
                }*/
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                const params = {
                    id: this.dataId,
                    upkeepItemIds: this.dataIds
                };
                return machineManagerUpkeepMachineJobMachineDetails(params).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res || {};
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    .no-data {
        width: 100%;
        font-size: 12px;
        color: #515a6e;
        text-align: center;
    }
</style>
